﻿(function (module) {
   
    module.directive('focusMe', function ($timeout) {
        return {
            link: function (scope, element, attrs) {
                $timeout(function () {
                    element[0].focus();
                }, 150);
            }
        };
    });
   
    module.directive('ionAmapPlace', [
    '$ionicTemplateLoader',
    '$ionicBackdrop',
    '$ionicPlatform',
    '$q',
    '$timeout',
    '$rootScope',
    '$document',
    function ($ionicTemplateLoader, $ionicBackdrop, $ionicPlatform, $q, $timeout, $rootScope, $document) {
        return {
            require: '?ngModel',
            restrict: 'E',
            template: '<input type="text" readonly="readonly" class="ion-amap-place" autocomplete="off">',
            replace: true,
            scope: {
                ngModel: '=?'
            },
            link: function (scope, element, attrs, ngModel) {
                var unbindBackButtonAction;

                scope.locations = [];


                var autocomplete;
                AMap.plugin('AMap.Autocomplete', function () { //回调函数
                    //实例化Autocomplete
                    var autoOptions = {
                        city: "" //城市，默认全国 
                    };
                    autocomplete = new AMap.Autocomplete(autoOptions);
                });

                //var geocoder = new google.maps.Geocoder();
                var searchEventTimeout = undefined;

                var POPUP_TPL = [
                    '<div class="ion-amap-place-container modal">',
                        '<div class="bar bar-header item-input-inset">',
                            '<label class="item-input-wrapper">',
                                '<i class="icon ion-ios7-search placeholder-icon"></i>',
                                '<input class="amap-place-search" type="search" ng-model="searchQuery" placeholder="' + (attrs.searchPlaceholder || '输入地址') + '">',
                            '</label>',
                            '<button class="button button-balanced">',
                                attrs.labelCancel || '取消',
                            '</button>',
                        '</div>',
                        '<ion-content class="has-header has-header">',
                            '<ion-list>',
                                '<ion-item ng-repeat="location in locations" type="item-text-wrap" ng-click="selectLocation(location)">',
                                    '{{location.name}}({{location.district}})',
                                '</ion-item>',
                            '</ion-list>',
                        '</ion-content>',
                    '</div>'
                ].join('');

                var popupPromise = $ionicTemplateLoader.compile({
                    template: POPUP_TPL,
                    scope: scope,
                    appendTo: $document[0].body
                });

                popupPromise.then(function (el) {
                    var searchInputElement = angular.element(el.element.find('input'));
                    scope.selectLocation = function (location) {
                        ngModel.$setViewValue(location);
                        el.element.css('display', 'none');
                        $ionicBackdrop.release();
                        if (unbindBackButtonAction) {
                            unbindBackButtonAction();
                            unbindBackButtonAction = null;
                        }
                    };
                    scope.$watch('searchQuery', function (query) {
                        if (searchEventTimeout) $timeout.cancel(searchEventTimeout);
                        searchEventTimeout = $timeout(function () {
                            if (!query) return;
                            if (query.length < 2) return;
                            autocomplete.search(query, function (status, result) {
                                if (status === "complete") {
                                    scope.$apply(function () {
                                        scope.locations = result.tips;
                                    });
                                } else {
                                    //todo
                                }
                            });
                            //geocoder.geocode(req, function (results, status) {
                            //    if (status == google.maps.GeocoderStatus.OK) {
                            //        scope.$apply(function () {
                            //            scope.locations = results;
                            //        });
                            //    } else {
                            //        // @TODO: Figure out what to do when the geocoding fails
                            //    }
                            //});
                        }, 350); // we're throttling the input by 350ms to be nice to google's API
                    });

                    var onClick = function (e) {
                        e.preventDefault();
                        e.stopPropagation();

                        $ionicBackdrop.retain();
                        unbindBackButtonAction = $ionicPlatform.registerBackButtonAction(closeOnBackButton, 250);
                        el.element.css('display', 'block');
                        searchInputElement[0].focus();
                        setTimeout(function () {
                            searchInputElement[0].focus();
                        }, 0);
                    };

                    var onCancel = function (e) {
                        scope.searchQuery = '';
                        $ionicBackdrop.release();
                        el.element.css('display', 'none');

                        if (unbindBackButtonAction) {
                            unbindBackButtonAction();
                            unbindBackButtonAction = null;
                        }
                    };

                    closeOnBackButton = function (e) {
                        e.preventDefault();

                        el.element.css('display', 'none');
                        $ionicBackdrop.release();

                        if (unbindBackButtonAction) {
                            unbindBackButtonAction();
                            unbindBackButtonAction = null;
                        }
                    }

                    element.bind('click', onClick);
                    element.bind('touchend', onClick);

                    el.element.find('button').bind('click', onCancel);
                });

                if (attrs.placeholder) {
                    element.attr('placeholder', attrs.placeholder);
                }


                ngModel.$formatters.unshift(function (modelValue) {
                    if (!modelValue) return '';
                    return modelValue;
                });

                ngModel.$parsers.unshift(function (viewValue) {
                    return viewValue;
                });

                ngModel.$render = function () {
                    if (!ngModel.$modelValue) {
                        element.val('');
                    } else {
                        element.val(ngModel.$modelValue.district + ngModel.$modelValue.name || '');
                    }
                };
                scope.$watch(function () {
                    return ngModel.$modelValue;
                }, function (modelValue) {
                    ngModel.$render();
                });

                scope.$on("$destroy", function () {
                    if (unbindBackButtonAction) {
                        unbindBackButtonAction();
                        unbindBackButtonAction = null;
                    }
                });
            }
        };
    }
    ]);

 
  

})(angular.module('app.directives'));